package com.masterclient.app.modules.goods;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselibrary.bean.goods.GoodDetailBean;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.R;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.widget.FlowLayout;
import com.masterclient.app.widget.KeyboardStatusDetector;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;

/**
 * 作者：sean
 * 创建时间：2017/7/10 14:42
 * 功能说明：
 */

public class SelectSkuDialog extends Dialog implements View.OnClickListener {

    List<GoodDetailBean.DataBean.ShAttributesBean> shAttributes;
    List<GoodDetailBean.DataBean.ShChildsBean> shChilds;
    private String defaultImage;
    private List<GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean> list;

    private Activity context;
    private List<FlowLayout> flowLayoutList;
    private String price, groupBuyPrice;
    private boolean isPromotion;

    public void setMiao(boolean miao) {
        isMiao = miao;
    }

    String point_sh_sype = "2";

    private boolean isMiao;//是否是秒杀

    public SelectSkuDialog(@NonNull Activity context, List<GoodDetailBean.DataBean.ShAttributesBean> shAttributes, List<GoodDetailBean.DataBean.ShChildsBean> shChilds, String defaultImage, String price, String groupBuyPrice, boolean isPromotion) {
        super(context, R.style.MyDialog);
        this.context = context;
        this.shAttributes = shAttributes;
        this.shChilds = shChilds;
        this.defaultImage = defaultImage;
        this.price = price;
        this.groupBuyPrice = groupBuyPrice;
        this.isPromotion = isPromotion;

    }

    public SelectSkuDialog(@NonNull Activity context, List<GoodDetailBean.DataBean.ShAttributesBean> shAttributes, List<GoodDetailBean.DataBean.ShChildsBean> shChilds, String defaultImage, String price, String groupBuyPrice, boolean isPromotion, String sh_type, String line_price) {
        super(context, R.style.MyDialog);
        this.context = context;
        this.shAttributes = shAttributes;
        this.shChilds = shChilds;
        this.defaultImage = defaultImage;
        this.price = price;
        fixed_price = price;
        this.groupBuyPrice = groupBuyPrice;
        this.isPromotion = isPromotion;
        this.sh_type = sh_type;
        this.line_price = line_price;
    }

    public SelectSkuDialog(@NonNull Activity context, List<GoodDetailBean.DataBean.ShAttributesBean> shAttributes, List<GoodDetailBean.DataBean.ShChildsBean> shChilds, String defaultImage, String price, String groupBuyPrice, boolean isPromotion, String sh_type, String line_price,String newPrice) {
        super(context, R.style.MyDialog);
        this.context = context;
        this.shAttributes = shAttributes;
        this.shChilds = shChilds;
        this.defaultImage = defaultImage;
        this.price = price;
        fixed_price = price;
        this.groupBuyPrice = groupBuyPrice;
        this.isPromotion = isPromotion;
        this.sh_type = sh_type;
        this.line_price = line_price;
        this.newPrice = newPrice;
    }

    private LinearLayout llSkuContainer, ll_earn;
    TextView tv_stock, tv_double_earn;
    RelativeLayout rl_close, rl_reduce, rl_plus;
    TextView tv_limit, tv_limit_quantity, tv_skus, tv_sku_title, tv_add_cart, tv_add_cart_0, tv_price, tv_price_now, tv_money_earn, tv_groupbuy_tag, tv_groupbuy_earn_tag, tv_original_price, tv_earn_divide;
    LinearLayout ll_group_price, ll_double_earn;
    EditText et_num;
    String sku_title = "";
    private ImageView iv_reduce, iv_plus, iv_goods;
    public int buyNum = 1;
    public int limitNum = 0;
    private long mStock;
    private String beforeStr;
    private String earn_money, partner_commission, fixed_price, line_price,newPrice, double_partner_commission, double_earn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sku_dialog);
        setCanceledOnTouchOutside(true);
        list = new ArrayList<>();
        flowLayoutList = new ArrayList<>();

        ll_double_earn = (LinearLayout) findViewById(R.id.ll_double_earn);
        tv_double_earn = (TextView) findViewById(R.id.tv_double_earn);
        llSkuContainer = (LinearLayout) findViewById(R.id.ll_sku_container);
        rl_close = (RelativeLayout) findViewById(R.id.rl_close);
        tv_stock = (TextView) findViewById(R.id.tv_stock);
        tv_skus = (TextView) findViewById(R.id.tv_skus);
        tv_sku_title = (TextView) findViewById(R.id.tv_sku_title);
        tv_add_cart = (TextView) findViewById(R.id.tv_add_cart);
        tv_add_cart_0 = (TextView) findViewById(R.id.tv_add_cart_0);
        iv_goods = (ImageView) findViewById(R.id.iv_goods);
        tv_price = (TextView) findViewById(R.id.tv_price);
        ll_earn = (LinearLayout) findViewById(R.id.ll_earn);
        tv_price_now = (TextView) findViewById(R.id.tv_price_now);
        tv_money_earn = (TextView) findViewById(R.id.tv_money_earn);
//        Utils.setDin(tv_money_earn, context);
        tv_earn_divide = (TextView) findViewById(R.id.tv_earn_divide);
        tv_groupbuy_tag = (TextView) findViewById(R.id.tv_groupbuy_tag);
        tv_groupbuy_earn_tag = (TextView) findViewById(R.id.tv_groupbuy_earn_tag);
        tv_original_price = (TextView) findViewById(R.id.tv_original_price);
        ll_group_price = (LinearLayout) findViewById(R.id.ll_group_price);
        findViewById(R.id.scrollView).getLayoutParams().height = (int) (ScreenUtils.getScreenHeight() * 2 / 5f);

        Utils.setDin(tv_price, context);
//        tv_original_price.setText("¥"+line_price);

        if (TextUtils.isEmpty(groupBuyPrice)) {
            tv_groupbuy_earn_tag.setVisibility(View.GONE);
            tv_groupbuy_tag.setVisibility(View.GONE);
            tv_original_price.setVisibility(View.GONE);
            if (point_sh_sype.equals(sh_type)) {
                set_point_price(tv_price, line_price, price);
            } else {
                //tv_price.setText("¥"+price);
                Utils.set_goodsdetail_price_style(tv_price, "¥ " + price);
            }
        } else {
            if (point_sh_sype.equals(sh_type)) {
                set_point_price(tv_price, line_price, groupBuyPrice);
            } else {
                tv_price.setText("¥ " + groupBuyPrice);
            }
//            tv_original_price.setText("¥"+price);
            tv_groupbuy_earn_tag.setVisibility(View.VISIBLE);
            tv_groupbuy_tag.setVisibility(View.VISIBLE);
            tv_original_price.setVisibility(View.VISIBLE);
            tv_original_price.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        }

        tv_add_cart.setOnClickListener(this);
        tv_add_cart_0.setOnClickListener(this);
        //App.picasso.load(defaultImage).resize(ScreenUtils.dp2px(100),ScreenUtils.dp2px(100)).transform(new PicassoRoundTransform()).into(iv_goods);
        GlideUtil.displayRoundImage(context, defaultImage, iv_goods, 7, R.mipmap.defaults);
        iv_goods.setOnClickListener(view -> {
            ArrayList<String> urlList = new ArrayList<>();
            urlList.add(defaultImage);
            Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.LOOK_PICTURE_FRAGMENT)
                    .withStringArrayList("urlList", urlList)
                    .withInt("position", 0)
                    .navigation();
            FragmentHostActivity.openFragment(context, fragment);
        });

        for (GoodDetailBean.DataBean.ShAttributesBean attr : shAttributes) {
            sku_title += (attr.getSh_label() + " ");
        }
        tv_sku_title.setText("请选择 ");
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mStock = checkStock(list);
        tv_stock.setText("库存：" + mStock + "件");


        if (mStock == 0) {
            set_sell_out();
        } else {
            set_normal_cart_btn();
        }

        initViews();
    }

    private void set_point_price(TextView tv_price, String price, String point) {
        String str1 = "金币";
        String str2 = " ";
        String str3 = "¥";
        String money = price;
        tv_price.setTextSize(17);
        String content = point + str1 + str2 + str3 + money;
        SpannableString spannableString = new SpannableString(content);
        spannableString.setSpan(new RelativeSizeSpan(0.75f), point.length(), content.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, point.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new StrikethroughSpan(), (point + str1 + str2).length(), content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#4d000000")), (point + str1 + str2).length(), content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_price.setText(spannableString);
    }

    private void set_normal_cart_btn() {
        tv_add_cart.setText(TextUtils.isEmpty(buttonName) ? "确认" : buttonName);
        if (sku_dialog_display_flag == 1 && !isPromotion) {
            tv_add_cart.setBackgroundResource(R.drawable.detail_buy_bkg0);
        } else {
            tv_add_cart.setBackgroundResource(R.drawable.detail_buy_bkg1);
        }
        tv_add_cart.setTextColor(Color.parseColor("#FFFFFF"));
    }

    private void set_sell_out() {
        tv_add_cart.setText("已售罄");
        tv_add_cart.setBackgroundResource(R.drawable.detail_sellout_bkg);
        tv_add_cart.setTextColor(Color.parseColor("#66000000"));
    }

    private void initViews() {
        llSkuContainer.removeAllViews();
        for (int i = 0; i < shAttributes.size(); i++) {
            GoodDetailBean.DataBean.ShAttributesBean bean = shAttributes.get(i);
            View view = View.inflate(context, R.layout.view_sku_condition_selector, null);
            TextView tv_label = (TextView) view.findViewById(R.id.tv_label);
            FlowLayout flowLayout = (FlowLayout) view.findViewById(R.id.flowLayout);
            flowLayoutList.add(flowLayout);
            tv_label.setText(bean.getSh_label());
            initSingleSku(bean, flowLayout);
            llSkuContainer.addView(view);
        }
        View line = new View(context);
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(0.5f));
        param.setMargins(0, ScreenUtils.dp2px(6), 0, 0);
        line.setLayoutParams(param);
        line.setBackgroundResource(R.color.gray_line);
        llSkuContainer.addView(line);

        View view_num = View.inflate(context, R.layout.view_sku_goods_num, null);

        if (!TextUtils.isEmpty(groupBuyPrice)) {//有拼团价就隐藏数量选择
            view_num.setVisibility(View.INVISIBLE);
            view_num.setClickable(false);
        } else {
            view_num.setVisibility(View.VISIBLE);//没有拼团价就显示
        }

        iv_plus = (ImageView) view_num.findViewById(R.id.iv_plus);
        iv_reduce = (ImageView) view_num.findViewById(R.id.iv_reduce);
        rl_reduce = (RelativeLayout) view_num.findViewById(R.id.rl_reduce);
        rl_reduce.setOnClickListener(this);
        rl_plus = (RelativeLayout) view_num.findViewById(R.id.rl_plus);
        rl_plus.setOnClickListener(this);
        et_num = (EditText) view_num.findViewById(R.id.et_num);
        Utils.setDin(et_num, context);
        tv_limit = (TextView) view_num.findViewById(R.id.tv_limit);
        tv_limit_quantity = (TextView) view_num.findViewById(R.id.tv_limit_quantity);

        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeStr = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().equals(beforeStr)) {
                    return;
                }
                if (!TextUtils.isEmpty(s)) {
                    Integer num = Integer.valueOf(s.toString());
                    buyNum = num;
                    changeReducePlus(num);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        et_num.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    buyNum = Integer.valueOf(et_num.getText().toString().trim());
                }
            }
        });
        llSkuContainer.addView(view_num);

        //所有商品库存都为0时，不可编辑数量
        if (0 == mStock) {
//            et_num.setText("0");
            et_num.setEnabled(false);
            iv_reduce.setImageResource(R.mipmap.sku_dialog_less_unclick_icon);
            //rl_reduce.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
            iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
            //rl_plus.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);

        }

        //只有一个sku，直接选中
        if (mStock >= 0 && shAttributes.size() == 1 && shAttributes.get(0).getSh_options().size() == 1) {
            LinearLayout ll_sku = (LinearLayout) llSkuContainer.getChildAt(0);
            FlowLayout flowLayout = (FlowLayout) ll_sku.getChildAt(1);
            TextView tv = (TextView) flowLayout.getChildAt(0);
            tv.performClick();
            if (!TextUtils.isEmpty(partner_commission) && Double.valueOf(partner_commission) > 0) {
                tv_money_earn.setText("赚" + partner_commission);
                tv_money_earn.setVisibility(View.VISIBLE);
                tv_earn_divide.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(double_partner_commission)&&
                        Float.parseFloat(double_partner_commission)>0) {
                    tv_money_earn.setVisibility(View.GONE);
                    ll_double_earn.setVisibility(View.VISIBLE);
                    tv_double_earn.setText(double_earn);
                }else {
                    ll_double_earn.setVisibility(View.GONE);
                }
            } else {
                ll_double_earn.setVisibility(View.GONE);
                tv_money_earn.setVisibility(View.GONE);
                tv_earn_divide.setVisibility(View.GONE);
            }
            setSh_type(sh_type);
        }


        new KeyboardStatusDetector().registerActivity(context).setmVisibilityListener(new KeyboardStatusDetector.KeyboardVisibilityListener() {
            @Override
            public void onVisibilityChanged(boolean keyboardVisible) {
                if (!keyboardVisible) {
                    if (TextUtils.isEmpty(et_num.getText().toString().trim())) {
                        et_num.setText("1");
                        buyNum = 1;
                    }
                }
            }
        });
    }

    private void changeReducePlus(Integer num) {
        rl_plus.setEnabled(true);
        iv_reduce.setImageResource(R.mipmap.sku_dialog_less_icon);
        //rl_reduce.setBackgroundResource(R.drawable.sku_add_sub_bkg);
        iv_plus.setImageResource(R.mipmap.sku_dialog_add_icon);
        //rl_plus.setBackgroundResource(R.drawable.sku_add_sub_bkg);

        if (num <= 1) {
            et_num.setText(1 + "");
            et_num.setSelection(1);
            iv_reduce.setImageResource(R.mipmap.sku_dialog_less_unclick_icon);
            //rl_reduce.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
        }
        if (num >= mStock) {
            et_num.setText(mStock + "");
            et_num.setSelection((mStock + "").length());
            iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
            //rl_plus.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
        }
    }

    private void initSingleSku(GoodDetailBean.DataBean.ShAttributesBean bean, FlowLayout flowLayout) {
        for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean optionBean : bean.getSh_options()) {
            TextView tv = (TextView) View.inflate(context, R.layout.tag_sku_unselect, null);
            tv.setText(optionBean.getSh_alias_name());
            ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(dp2px(0), dp2px(0), dp2px(10), dp2px(10));
            tv.setMinWidth(ScreenUtils.dp2px(74));
            flowLayout.addView(tv, lp);

            long stock = checkHave(bean, optionBean);

            if (stock > 0) { //该属性的库存大于0
                for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean attr : list) {
                    if (attr.getSh_option_id().equals(optionBean.getSh_option_id())) {
                        tv.setBackgroundResource(R.drawable.sku_selected);
                        tv.setTextColor(context.getResources().getColor(R.color.our_gongzhu_color));
                        break;
                    } else {
                        tv.setBackgroundResource(R.drawable.shape_round_f0f2f5);
                        tv.setTextColor(Color.parseColor("#141922"));
                    }
                }

                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean selected = false;
                        for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean attr : list) {
                            if (attr.getSh_option_id().equals(optionBean.getSh_option_id())) {
                                selected = true;
                                break;
                            }
                        }

                        if (selected) {//该按钮是否已经被选中
                            tv.setBackgroundResource(R.drawable.shape_round_f0f2f5);
                            list.remove(optionBean);
                            for (int i = 0; i < shAttributes.size(); i++) {
                                GoodDetailBean.DataBean.ShAttributesBean shBean = shAttributes.get(i);
                                flowLayoutList.get(i).removeAllViews();
                                initSingleSku(shBean, flowLayoutList.get(i));
                            }
                        } else {


//                            price =
                            tv.setBackgroundResource(R.drawable.sku_selected);
                            removeSelectSku(bean);
                            list.add(optionBean);
//                          initViews();
//                            flowLayout.removeAllViews();
                            for (int i = 0; i < shAttributes.size(); i++) {
                                GoodDetailBean.DataBean.ShAttributesBean shBean = shAttributes.get(i);
                                flowLayoutList.get(i).removeAllViews();
                                initSingleSku(shBean, flowLayoutList.get(i));
                            }
                            if (!TextUtils.isEmpty(optionBean.getSh_image())) {
                                //App.picasso.load(optionBean.getSh_image()).resize(ScreenUtils.dp2px(100),ScreenUtils.dp2px(100)).transform(new NewPicassoRoundTransform(6)).into(iv_goods);
                                GlideUtil.displayRoundImage(context, optionBean.getSh_image(), iv_goods, 7, R.mipmap.defaults);
                            } else {
                                //App.picasso.load(defaultImage).resize(ScreenUtils.dp2px(100),ScreenUtils.dp2px(100)).transform(new NewPicassoRoundTransform(6)).into(iv_goods);
                                GlideUtil.displayRoundImage(context, defaultImage, iv_goods, 7, R.mipmap.defaults);
                            }
                        }
                        mStock = checkStock(list);
                        GoodDetailBean.DataBean.ShChildsBean childBean = checkPrice(list);

                        if (childBean != null) {
                            if (!TextUtils.isEmpty(childBean.getSh_image())) {
                                //App.picasso.load(childBean.getSh_image()).resize(ScreenUtils.dp2px(100),ScreenUtils.dp2px(100)).transform(new NewPicassoRoundTransform(6)).into(iv_goods);
                                GlideUtil.displayRoundImage(context, childBean.getSh_image(), iv_goods, 7, R.mipmap.defaults);
                            } else {
                                //App.picasso.load(defaultImage).resize(ScreenUtils.dp2px(100),ScreenUtils.dp2px(100)).transform(new NewPicassoRoundTransform(6)).into(iv_goods);
                                GlideUtil.displayRoundImage(context, defaultImage, iv_goods, 7, R.mipmap.defaults);
                            }
                            ll_group_price.setVisibility(View.VISIBLE);
                            ll_earn.setVisibility(View.GONE);
                            if (TextUtils.isEmpty(childBean.getSh_partner_commission()) || 0 == Double.valueOf(childBean.getSh_partner_commission())) {
                                if (isPromotion) {
                                    if (!TextUtils.isEmpty(childBean.getSh_promotion_price())) {
                                        //tv_price.setText("¥"+childBean.getSh_promotion_price());
                                        if (point_sh_sype.equals(sh_type)) {
                                            set_point_price(tv_price, childBean.getSh_line_price(), childBean.getSh_integral_price());
                                        } else {
                                            //tv_price.setText("¥"+childBean.getSh_promotion_price());
                                            Utils.set_goodsdetail_price_style(tv_price, "¥ " + childBean.getSh_promotion_price());
                                        }
                                    } else {
                                        //tv_price.setText(SelectSkuDialog.this.price);
                                        if (point_sh_sype.equals(sh_type)) {
                                            set_point_price(tv_price, SelectSkuDialog.this.price, SelectSkuDialog.this.price);
                                        } else {
                                            //tv_price.setText("¥"+SelectSkuDialog.this.price);
                                            Utils.set_goodsdetail_price_style(tv_price, "¥ " + SelectSkuDialog.this.price);
                                        }
                                    }
                                } else {
                                    if (!TextUtils.isEmpty(childBean.getSh_no_promotion_show_price())) {
                                        //tv_price.setText("¥"+childBean.getSh_no_promotion_show_price());
                                        if (point_sh_sype.equals(sh_type)) {
                                            set_point_price(tv_price, childBean.getSh_line_price(), childBean.getSh_integral_price());
                                        } else {
                                            //tv_price.setText("¥"+childBean.getSh_no_promotion_show_price());
                                            Utils.set_goodsdetail_price_style(tv_price, "¥ " + childBean.getSh_no_promotion_show_price());
                                        }
                                    } else {
                                        //tv_price.setText(SelectSkuDialog.this.price);
                                        if (point_sh_sype.equals(sh_type)) {
                                            set_point_price(tv_price, SelectSkuDialog.this.line_price, SelectSkuDialog.this.price);
                                        } else {
                                            //tv_price.setText("¥"+SelectSkuDialog.this.price);
                                            Utils.set_goodsdetail_price_style(tv_price, "¥ " + SelectSkuDialog.this.price);
                                        }
                                    }
                                }

                            } else {
//                                if(isPromotion){
//                                    tv_price_now.setText("¥"+childBean.getSh_show_price());
//                                    tv_money_earn.setText("赚"+childBean.getSh_partner_commission());
//                                    tv_money_earn.setVisibility(View.VISIBLE);
//                                    tv_earn_divide.setVisibility(View.VISIBLE);
//                                }else {
                                //tv_price.setText("¥"+childBean.getSh_no_promotion_show_price());
                                if (!TextUtils.isEmpty(newPrice)){
                                    Utils.set_goodsdetail_price_style(tv_price, "¥ " + newPrice);
                                }else {
                                    Utils.set_goodsdetail_price_style(tv_price, "¥ " + childBean.getSh_show_price());
                                }
                                if (Double.valueOf(childBean.getSh_partner_commission()) > 0) {
                                    tv_money_earn.setText("赚" + childBean.getSh_partner_commission());
                                    tv_money_earn.setVisibility(View.VISIBLE);
                                    tv_earn_divide.setVisibility(View.VISIBLE);
                                    if (!TextUtils.isEmpty(double_partner_commission)&&
                                            Float.parseFloat(double_partner_commission)>0
                                            &&!TextUtils.isEmpty(childBean.getSh_double_partner_commission())&&
                                            Float.parseFloat(childBean.getSh_double_partner_commission())>0) {
                                        tv_money_earn.setVisibility(View.GONE);
                                        ll_double_earn.setVisibility(View.VISIBLE);
                                        tv_double_earn.setText("赚" + childBean.getSh_double_partner_commission());
                                    }else {
                                        ll_double_earn.setVisibility(View.GONE);
                                    }
                                } else {
                                    tv_money_earn.setVisibility(View.GONE);
                                    tv_earn_divide.setVisibility(View.GONE);
                                }
                                setSh_type(sh_type);
//                                }

                            }
                        } else {
//                            ll_group_price.setVisibility(View.GONE);
//                            ll_earn.setVisibility(View.VISIBLE);
                            //tv_price.setText("¥"+fixed_price);
                            //App.picasso.load(defaultImage).resize(ScreenUtils.dp2px(100),ScreenUtils.dp2px(100)).transform(new NewPicassoRoundTransform(6)).into(iv_goods);
                            GlideUtil.displayRoundImage(context, defaultImage, iv_goods, 7, R.mipmap.defaults);
                            if (point_sh_sype.equals(sh_type)) {
                                set_point_price(tv_price, line_price, fixed_price);
                            } else {
                                Utils.set_goodsdetail_price_style(tv_price, "¥ " + fixed_price);
                            }

                            tv_groupbuy_tag.setVisibility(View.GONE);
                            tv_original_price.setVisibility(View.GONE);
                            tv_money_earn.setText(earn_money);
                            if (TextUtils.isEmpty(partner_commission) || 0 == Double.valueOf(partner_commission)) {
                                tv_money_earn.setVisibility(View.GONE);
                                tv_earn_divide.setVisibility(View.GONE);
                            } else {
                                tv_money_earn.setVisibility(View.VISIBLE);
                                tv_earn_divide.setVisibility(View.VISIBLE);
                                if (!TextUtils.isEmpty(double_partner_commission)&&
                                        Float.parseFloat(double_partner_commission)>0
                                        &&!TextUtils.isEmpty(double_partner_commission)&&
                                        Float.parseFloat(double_partner_commission)>0) {
                                    tv_money_earn.setVisibility(View.GONE);
                                    ll_double_earn.setVisibility(View.VISIBLE);
                                    tv_double_earn.setText(double_earn);
                                }else {
                                    ll_double_earn.setVisibility(View.GONE);
                                }
                            }
                            setSh_type(sh_type);
                        }


                        tv_stock.setText("库存：" + mStock + "件");
                        if (mStock == 0) {
                            set_sell_out();
                        } else {
                            set_normal_cart_btn();
                        }
                        showSkusText();
                    }
                });
            } else { //该属性的库存小于0
                tv.setBackgroundResource(R.drawable.sku_canot_select);
                tv.setTextColor(0xffc2c5cc);
            }
        }


    }

    private GoodDetailBean.DataBean.ShChildsBean checkPrice(List<GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean> list) {

        GoodDetailBean.DataBean.ShChildsBean temp = null;

        if (list.size() == shAttributes.size()) {
            HashSet<String> skuSet = new HashSet<>();
            for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean bean : list) {
                skuSet.add(bean.getSh_option_id());
            }
            for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                int count = 0;
                String[] skus = bean.getSh_sku_code().split("_");
                for (String s : skus) {
                    if (skuSet.contains(s)) {
                        count++;
                    }
                }
                if (count == skus.length) {
                    temp = bean;
                }
            }
        }
        return temp;

    }

    private void showSkusText() {
        if (list.size() == 0) {
            tv_skus.setText("");
            tv_sku_title.setText("请选择 " + sku_title);
        } else {
            tv_sku_title.setText("已选择：");
            String sku_txt = "";
            for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean optionBean : list) {
                sku_txt += ("“" + optionBean.getSh_alias_name() + "”");
            }
            tv_skus.setText(sku_txt);
        }


    }

    //删除已选中的同一行的sku
    private void removeSelectSku(GoodDetailBean.DataBean.ShAttributesBean bean) {

        for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean optionBean : bean.getSh_options()) {
            GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean option = null;
            for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean s : list) {
                if (s.getSh_option_id().equals(optionBean.getSh_option_id())) {
                    option = s;
                }
            }
            if (option != null) {
                list.remove(option);
            }
        }
    }

    /**
     * 检查是否有该属性的商品，最多两个sku
     *
     * @param optionBean
     */
    private long checkHave(GoodDetailBean.DataBean.ShAttributesBean attrBean, GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean optionBean) {
        long stock_num = 0;


        if (list.size() == 0) {//未选中sku时库存
            if (shAttributes.size() == 1) {//只有一行属性
                for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                    String[] skus = bean.getSh_sku_code().split("_");
                    for (String s : skus) {
                        if (s.equals(optionBean.getSh_option_id())) {
                            stock_num += Long.valueOf(getStock(bean));
                        }
                    }
                }
                return stock_num;
            } else {//两行属性
                return 1;
            }

        } else if (list.size() == 1) {//选择一个sku时，和每个未选中sku的虚拟组合的sku的库存，为了检查按钮是否可点击
            if (attrBean.getSh_label().equals(list.get(0).getSh_name())) { //同一行的sku,设置为有库存
                if (shAttributes.size() == 1) {//一行sku
                    for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                        String[] skus = bean.getSh_sku_code().split("_");
                        for (String s : skus) {
                            if (s.equals(optionBean.getSh_option_id())) {
                                stock_num += Long.valueOf(getStock(bean));
                            }
                        }
                    }
                    return stock_num;
                } else {//同一行的sku,设置为有库存,两行sku
                    return 1;
                }
            }

            for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                String[] skus = bean.getSh_sku_code().split("_");
                Set<String> set = new HashSet<>();
                for (String s : skus) {
                    set.add(s);
                }

                if (set.contains(optionBean.getSh_option_id()) && set.contains(list.get(0).getSh_option_id())) { //不同行的计算个数
                    stock_num += Long.valueOf(getStock(bean));
                }
            }
        } else if (list.size() == 2) {//选中两个sku时,该sku的库存
            if (!attrBean.getSh_label().equals(list.get(0).getSh_name())) {

                for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                    String[] skus = bean.getSh_sku_code().split("_");
                    Set<String> set = new HashSet<>();
                    for (String s : skus) {
                        set.add(s);
                    }
                    if (set.contains(optionBean.getSh_option_id()) && set.contains(list.get(0).getSh_option_id())) {
                        stock_num += Long.valueOf(getStock(bean));
                    }
                }
            }

            if (!attrBean.getSh_label().equals(list.get(1).getSh_name())) {
                for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                    String[] skus = bean.getSh_sku_code().split("_");
                    Set<String> set = new HashSet<>();
                    for (String s : skus) {
                        set.add(s);
                    }
                    if (set.contains(optionBean.getSh_option_id()) && set.contains(list.get(1).getSh_option_id())) {
                        stock_num += Long.valueOf(getStock(bean));
                    }
                }
            }
        }
        return stock_num;
    }

    /**
     * 获取指定sku组合的库存
     *
     * @param list
     * @return
     */
    private long checkStock(List<GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean> list) {
        long stock_num = 0;
        if (list.size() == 0) {
            for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                stock_num += Long.valueOf(getStock(bean));
            }
        }

        if (list.size() > 0) {
            for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                String[] skus = bean.getSh_sku_code().split("_");

                boolean selected = true;

                HashSet set = new HashSet();
                for (String s : skus) {
                    set.add(s);
                }

                for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean sku : list) {
                    if (!set.contains(sku.getSh_option_id())) {
                        selected = false;
                        break;
                    }
                }
                if (selected) {
                    stock_num += Long.valueOf(getStock(bean));
                }
            }
        }

        return stock_num;
    }

    private String getStock(GoodDetailBean.DataBean.ShChildsBean bean) {
        if (isMiao) {//秒杀库存
            return bean.getSh_stock();
        } else {//原价库存
            return bean.getSh_no_promotion_stock();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        window.setWindowAnimations(R.style.bottomShow);
        WindowManager.LayoutParams windowparams = window.getAttributes();

        window.setGravity(Gravity.BOTTOM);
        windowparams.width = ScreenUtils.getScreenWidth();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setAttributes(windowparams);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_reduce:
                if (buyNum == 1) {//至少购买一件商品
                    showToast("至少购买一件");
                } else {
                    buyNum--;
                    et_num.setText(buyNum + "");
//                    changeReducePlus(buyNum);
                }
                break;
            case R.id.rl_plus:
                //有限购
                if (limitNum > 0) {
                    //1、限购数量>=库存
                    if (limitNum >= mStock) {
                        if (buyNum < mStock) {
                            buyNum++;
                            et_num.setText(buyNum + "");
                        } else {//已经达到库存上线
                            rl_plus.setEnabled(false);
                            iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
                            showToast("已达到库存上限");
                        }
                    } else {
                        //2、限购数量<库存
                        if (buyNum < limitNum) {
                            buyNum++;
                            et_num.setText(buyNum + "");
                        } else {//已经达到库存上线
                            rl_plus.setEnabled(false);
                            iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
                            showToast("已达到限购上限");
                        }
                    }
                } else {
                    //无限购
                    if (buyNum < mStock) {
                        buyNum++;
                        et_num.setText(buyNum + "");
//                    changeReducePlus(buyNum);
                    } else {//已经达到库存上线
                        rl_plus.setEnabled(false);
                        iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
                        showToast("已达到库存上限");
                    }
                }
                break;
            case R.id.tv_add_cart:
                if (addCartClickListerner != null) {
                    if (list.size() < shAttributes.size()) {
                        Toast.makeText(context, "请选择商品属性", Toast.LENGTH_SHORT).show();
                    } else {
                        first:
                        for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                            String[] skus = bean.getSh_sku_code().split("_");
                            Set<String> set = new HashSet<>();
                            for (String s : skus) {
                                set.add(s);
                            }
                            for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean optionsBean : list) {
                                if (!set.contains(optionsBean.getSh_option_id())) {
                                    continue first;
                                }
                            }
                            String etNum = et_num.getText().toString().trim();
                            addCartClickListerner.addCart(bean.getSh_id(), etNum, 1);
                            break;
                        }
                    }
                }
                break;
            case R.id.tv_add_cart_0:
                if (addCartClickListerner != null) {
                    if (list.size() < shAttributes.size()) {
                        Toast.makeText(context, "请选择商品属性", Toast.LENGTH_SHORT).show();
                    } else {
                        first:
                        for (GoodDetailBean.DataBean.ShChildsBean bean : shChilds) {
                            String[] skus = bean.getSh_sku_code().split("_");
                            Set<String> set = new HashSet<>();
                            for (String s : skus) {
                                set.add(s);
                            }
                            for (GoodDetailBean.DataBean.ShAttributesBean.ShOptionsBean optionsBean : list) {
                                if (!set.contains(optionsBean.getSh_option_id())) {
                                    continue first;
                                }
                            }
                            String etNum = et_num.getText().toString().trim();
                            addCartClickListerner.addCart(bean.getSh_id(), etNum, 0);
                            break;
                        }
                    }
                }
                break;
        }
    }

    public void zeroGet() {
        tv_limit.setVisibility(View.VISIBLE);
        rl_reduce.setEnabled(false);
        rl_plus.setEnabled(false);
        et_num.setEnabled(false);
        iv_reduce.setImageResource(R.mipmap.sku_dialog_less_unclick_icon);
        //rl_reduce.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
        iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
        //rl_plus.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
    }

    public void giftGet() {
        tv_limit.setVisibility(View.VISIBLE);
        tv_limit.setText("限购1件");
        rl_reduce.setEnabled(false);
        rl_plus.setEnabled(false);
        et_num.setEnabled(false);
        iv_reduce.setImageResource(R.mipmap.sku_dialog_less_unclick_icon);
        //rl_reduce.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
        iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
        //rl_plus.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);

    }

    public void updateLimit(String num) {
        limitNum = Integer.parseInt(num);
        tv_limit_quantity.setVisibility(View.VISIBLE);
        tv_limit_quantity.setText("(限购" + num + "件)");
        if (Integer.parseInt(num) <= 1) {
            rl_reduce.setEnabled(false);
            rl_plus.setEnabled(false);
            et_num.setEnabled(false);
            iv_reduce.setImageResource(R.mipmap.sku_dialog_less_unclick_icon);
            //rl_reduce.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
            iv_plus.setImageResource(R.mipmap.sku_dialog_add_unclick_icon);
            //rl_plus.setBackgroundResource(R.drawable.sku_add_sub_unclick_bkg);
        }
    }

    String sh_type = "";

    public String getSh_type() {
        return sh_type;
    }

    public void setSh_type(String sh_type) {
        this.sh_type = sh_type;

        if ("4".equals(sh_type) || "3".equals(sh_type)
                || "2".equals(sh_type) || TextUtils.isEmpty(partner_commission) || Double.valueOf(partner_commission) <= 0) {
            tv_money_earn.setVisibility(View.GONE);
            tv_earn_divide.setVisibility(View.GONE);
        } else {
            tv_money_earn.setVisibility(View.VISIBLE);
            tv_earn_divide.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(double_partner_commission)&&
                    Float.parseFloat(double_partner_commission)>0) {
                tv_money_earn.setVisibility(View.GONE);
                ll_double_earn.setVisibility(View.VISIBLE);
            }else {
                ll_double_earn.setVisibility(View.GONE);
            }
        }
    }

    String buttonName;
    int sku_dialog_display_flag;

    public void setConfirmButtonName(String buttonName, int sku_dialog_display_flag) {
        this.buttonName = buttonName;
        this.sku_dialog_display_flag = sku_dialog_display_flag;
        if (sku_dialog_display_flag == 1 && !isPromotion) {
            tv_add_cart_0.setVisibility(View.VISIBLE);
            tv_add_cart.setBackgroundResource(R.drawable.detail_buy_bkg0);
        } else {
            tv_add_cart_0.setVisibility(View.GONE);
            tv_add_cart.setBackgroundResource(R.drawable.detail_buy_bkg1);
        }
        if (mStock != 0) {
            tv_add_cart.setText(buttonName);
        }
    }

    public void setAddCartClickListerner(AddCartClickListerner addCartClickListerner) {
        this.addCartClickListerner = addCartClickListerner;
    }

    private AddCartClickListerner addCartClickListerner;

    public interface AddCartClickListerner {
        public void addCart(String skus, String num, int operate);//operate 0 加入购物车 1 立刻购买
    }

    public void showToast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }

    public void showPartner(String sell_price, String earn_money, String partner_commission, String double_partner_commission, String double_earn) {
//        tv_price.setVisibility(View.GONE);
//        ll_group_price.setVisibility(View.GONE);
//        ll_earn.setVisibility(View.VISIBLE);
        tv_price_now.setText(sell_price);
        tv_money_earn.setText(earn_money);
        this.earn_money = earn_money;
        this.partner_commission = partner_commission;
        this.double_earn = double_earn;
        this.double_partner_commission = double_partner_commission;
        if (!TextUtils.isEmpty(partner_commission) && 0 == Double.valueOf(partner_commission)) {
            tv_money_earn.setVisibility(View.GONE);
            ll_double_earn.setVisibility(View.GONE);
            tv_earn_divide.setVisibility(View.GONE);
        } else {
            tv_money_earn.setVisibility(View.VISIBLE);
            tv_earn_divide.setVisibility(View.VISIBLE);

            if (!TextUtils.isEmpty(double_partner_commission)&&
                    Float.parseFloat(double_partner_commission)>0) {
                tv_money_earn.setVisibility(View.GONE);
                ll_double_earn.setVisibility(View.VISIBLE);
                tv_double_earn.setText(double_earn);
            }else {
                ll_double_earn.setVisibility(View.GONE);
            }
        }
//        if(0 == Double.valueOf(earn_money.substring(1))){
//            tv_money_earn.setVisibility(View.GONE);
//            tv_earn_divide.setVisibility(View.GONE);
//        }
    }
}
